package apptoko.com.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import apptoko.com.LoginActivity;
import apptoko.com.ReviewActivity;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.GetCommentSuccessEvent;
import apptoko.com.event.Event.GetCommentsFailEvent;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.model.CommentItem;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;
import apptoko.com.view.LoadMoreListView;
import apptoko.com.view.LoadMoreListView.OnLoadMoreListener;

import com.androidquery.AQuery;
import apptoko.com.R;

import de.greenrobot.event.EventBus;

public class CommentsFragment extends BaseFragment implements OnLoadMoreListener, OnClickListener{
	
	private AQuery aq;
	private BackgroundTasks bgTask;
	private String appId;
	private CommentAdapter adapter;
	private List<CommentItem> commentList;
	private LoadMoreListView listView;
	private int START = 0;
	private EventBus eventBus;
	private Button btnWriteComment;
	public static int REVIEW_RETURN_CODE=1312;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mParent = inflater.inflate(R.layout.layout_comments, null);
		aq = new AQuery(mParent);
		listView = (LoadMoreListView) mParent.findViewById(R.id.list_comment);
		View v = inflater.inflate(R.layout.btn_write_comment, null);
		btnWriteComment = (Button) v.findViewById(R.id.write_comment);
		listView.addHeaderView(v);
		aq.id(listView).adapter(adapter);
		listView.setOnLoadMoreListener(this);
		return mParent;
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		eventBus = EventBus.getDefault();
		bgTask = new BackgroundTasks(mContext);
		appId = getArguments().getString(Constants.SLUG);
		commentList = new ArrayList<CommentItem>();
		adapter = new CommentAdapter(mContext, R.layout.comment_item, commentList);
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		bgTask.getComments(Utils.getStaticAccessToken(getActivity()), appId, START);
	}
	
	public void onEventMainThread(GetCommentSuccessEvent event){
		//if(event.getCommentList().size() > 0){
			commentList.clear();
			for(CommentItem comment : event.getCommentList()){
				commentList.add(comment);
			}
			adapter.notifyDataSetChanged();
			aq.id(R.id.comment_progress).gone();
			aq.id(R.id.btn_retry_cmt).gone();
			aq.id(R.id.txt_no_comment).gone();
			btnWriteComment.setOnClickListener(this);
			aq.id(R.id.list_comment).visible();
			listView.onLoadMoreComplete();
	}
	
	public void onEventMainThread(RequestFailEvent event){
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
		aq.id(R.id.comment_progress).gone();
		aq.id(R.id.btn_retry_cmt).visible().clicked(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				aq.id(R.id.comment_progress).visible();
				aq.id(R.id.btn_retry_cmt).gone();
				aq.id(R.id.txt_no_comment).gone();
				if(Utils.getStaticIsLogin(getActivity())){
					bgTask.getComments(Utils.getStaticAccessToken(getActivity()), appId, 0);
				} else {
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								Intent intent = new Intent(getActivity(), LoginActivity.class);
								startActivity(intent);
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				}
			}
		});
		aq.id(R.id.txt_no_comment).gone();
		aq.id(R.id.list_comment).gone();
		aq.id(R.id.write_comment).gone();
		listView.setOnLoadMoreListener(null);
	}
	
	public void onEventMainThread(GetCommentsFailEvent e){
		if(START == 0){
			//AppMsg.makeText(getActivity(), e.getMessage(), AppMsg.STYLE_ALERT, null).show();
			aq.id(R.id.txt_no_comment).visible();
			aq.id(R.id.list_comment).visible();
			aq.id(R.id.write_comment).visible().clicked(this);
			aq.id(R.id.comment_progress).gone();
		}
		listView.onLoadMoreComplete();
		listView.setOnLoadMoreListener(null);
	}
	
	private class CommentAdapter extends ArrayAdapter<CommentItem> {
		
		private LayoutInflater inflater;
		private AQuery aq;

		public CommentAdapter(Context context, int resource, List<CommentItem> list) {
			super(context, resource, list);
			// TODO Auto-generated constructor stub
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				convertView = inflater.inflate(R.layout.comment_item, null);
				holder = new ViewHolder();
				holder.content = (TextView) convertView.findViewById(R.id.comment_content);
				holder.rating = (RatingBar) convertView.findViewById(R.id.comment_rating_bar);
				holder.time = (TextView) convertView.findViewById(R.id.comment_time);
				holder.userName = (TextView) convertView.findViewById(R.id.comment_user);
				holder.editat=(TextView)convertView.findViewById(R.id.editat);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			CommentItem comment = getItem(position);
			if(comment != null){
				aq = new AQuery(convertView);
				aq.id(holder.content).text(Html.fromHtml(comment.getContent().replace("\\n", "<br/>").replace("\n", "<br/>")));
				aq.id(holder.rating).rating(comment.getRate());
				aq.id(holder.time).text(comment.getPost_time()<comment.getLast_update()?Utils.convertUnixTime(String.valueOf(comment.getLast_update())):Utils.convertUnixTime(String.valueOf(comment.getPost_time())));
				if(comment.getPost_time()<comment.getLast_update()){
					aq.id(holder.editat).text("editted at");
				}else{
					aq.id(holder.editat).text("at");
				}
				aq.id(holder.userName).text(comment.getUsername());
			}
			return convertView;
		}
	}
	
	private static class ViewHolder {
		RatingBar rating;
		TextView userName;
		TextView time;
		TextView content;
		TextView editat;
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		START = START + 20;
		bgTask.getComments(Utils.getStaticAccessToken(getActivity()), appId, START);
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		eventBus.register(this);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		eventBus.unregister(this);
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==REVIEW_RETURN_CODE &&  resultCode== Activity.RESULT_OK){
			bgTask.getComments(Utils.getStaticAccessToken(getActivity()), appId, 0);
		}
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.write_comment:
			if(Utils.getStaticIsLogin(getActivity())){
				Intent i = new Intent(getActivity(), ReviewActivity.class);
				i.putExtra(Constants.SLUG, appId);
				String username=getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getString(Constants.USERNAME_LOGGEDIN, "");
				if(!TextUtils.isEmpty(username)){
					CommentItem mine=null;
					for (CommentItem comment : commentList) {
						if(comment.getUsername().equalsIgnoreCase(username)){
							mine=comment;
							break;
						}
					}
					if(mine!=null){
						i.putExtra("review", mine.getContent());
						i.putExtra("rate", mine.getRate());
					}
				}
				startActivityForResult(i,REVIEW_RETURN_CODE);
			} else {
				AlertDialogManager am = new AlertDialogManager(getActivity());
				am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							Intent intent = new Intent(getActivity(), LoginActivity.class);
							startActivity(intent);
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						}
					}
				});
			}
			break;
		default:
			break;
		}
	}
}
